#!/usr/bin/env bash

# This file is part of The RetroPie Project
#
# The RetroPie Project is the legal property of its developers, whose names are
# too numerous to list here. Please refer to the COPYRIGHT.md file distributed with this source.
#
# See the LICENSE.md file at the top-level directory of this distribution and
# at https://raw.githubusercontent.com/RetroPie/RetroPie-Setup/master/LICENSE.md
#

rp_module_id="minivmac"
rp_module_desc="Macintosh Plus Emulator"
rp_module_help="ROM Extensions: .dsk \n\nCopy your Macintosh Plus disks to $romdir/macintosh \n\n You need to copy the Macintosh bios file vMac.ROM into "$biosdir" and System Tools.dsk to $romdir"
rp_module_licence="GPL2 https://raw.githubusercontent.com/minivmac/minivmac/refs/heads/master/COPYING.txt"
rp_module_repo="git https://github.com/minivmac/minivmac.git master"
rp_module_section="exp"
rp_module_flags=""

function depends_minivmac() {
    getDepends libsdl2-dev
}

function sources_minivmac() {
    gitPullOrClone
}

function __cpu_minivmac() {
    if isPlatform "64bit"; then
        isPlatform "aarch64" && echo "a64"
        isPlatform "x86" && echo "x64"
    else
        isPlatform "arm" && echo "arm"
        isPlatform "x86" && echo "x86"
    fi
}
function __target_minivmac() {
    isPlatform "arm" || isPlatform "aarch64" && echo "larm"
    isPlatform "x86" && ! isPlatform "64bit" && echo "lx86"
    isPlatform "x86" && isPlatform "64bit" && echo "lx64"
}

function build_minivmac() {
    cc -o setup_t setup/tool.c
    local em_speed=4
    isPlatform "armv6" && em_speed=2

    ./setup_t \
        -maintainer "egon.rath@gmail.com" \
        -homepage "https://github.com/egrath" \
        -t "$(__target_minivmac)" \
        -cpu "$(__cpu_minivmac)" \
        -e bgc \
        -hres 640 -vres 480 -depth 0 \
        -magnify 1 -mf 2 \
        -m Plus \
        -sound 1 \
        -sony-sum 1 -sony-tag 1 \
        -speed $em_speed -ta 2 -em-cpu 2 \
        -chr 0 -drc 1 -sss 4 \
        -fullscreen 1 \
        -var-fullscreen 1 \
        -api sd2 \
        > setup.sh

    bash setup.sh
    # amend the CFLAGS auto-generated by the build system
    sed -i "s/^mk_COptions =.*/mk_COptions = \$(mk_COptionsCommon) $CFLAGS/" Makefile
    make clean
    make

    md_ret_require="$md_build/minivmac"
}

function install_minivmac() {
    md_ret_files=(
        'minivmac'
        'COPYING.txt'
        'README.md'
        'README.txt'
    )
}

function configure_minivmac() {
    mkRomDir "macintosh"

    ln -sf "$biosdir/vMac.ROM" "$md_inst/vMac.ROM"

    addEmulator 1 "$md_id" "macintosh" "pushd $md_inst; $md_inst/minivmac $romdir/macintosh/System\ Tools.dsk %ROM%; popd"
    addSystem "macintosh"
}
